package com.senseuni.da.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.senseuni.da.R;
import com.senseuni.da.model.SettingMenuItem;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class SettingMenuAdapter extends RecyclerView.Adapter<SettingMenuAdapter.MyViewHolder> {

    private final Context mContext;
    private List<SettingMenuItem> mDataList;

    private int mCurrentSelectionIndex = 0;

    public SettingMenuAdapter(Context context) {
        this.mContext = context;
        mDataList = new ArrayList<>();
    }

    public void setDataList(List<SettingMenuItem> list) {
        mDataList = list;
    }

    public SettingMenuItem getItem(int position) {
        return mDataList.get(position);
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_setting_menu_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        holder.itemView.setOnClickListener(v -> {
            int position = holder.getLayoutPosition();
            if (position == mCurrentSelectionIndex) {
                return;
            }
            if (mItemClickListener != null) {
                mItemClickListener.onItemClick(getItem(position), position);
                int lastSelectionIndex = mCurrentSelectionIndex;
                mCurrentSelectionIndex = position;
                notifyItemChanged(lastSelectionIndex);
                notifyItemChanged(mCurrentSelectionIndex);
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        SettingMenuItem item = mDataList.get(position);
        holder.mTitleView.setText(item.getTitle());
        holder.mImageView.setImageResource(item.getIcon());

        holder.itemView.setSelected(position == mCurrentSelectionIndex);
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView mImageView;
        TextView mTitleView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mImageView = itemView.findViewById(R.id.image_view);
            mTitleView = itemView.findViewById(R.id.title_view);
        }
    }

    public interface OnSettingMenuItemClickListener {
        void onItemClick(SettingMenuItem item, int position);
    }

    public OnSettingMenuItemClickListener mItemClickListener;

    public void setOnItemClickListener(OnSettingMenuItemClickListener listener) {
        mItemClickListener = listener;
    }
}
